import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { NzMessageService, NzModalRef, UploadFile } from 'ng-zorro-antd';
import { FormBuilder, FormControl, FormGroup,  Validators } from '@angular/forms';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { SFSchema, SFUISchema } from '@delon/form';
import { UtilService } from '@core/services/util.service';
import * as $ from 'jquery';
import { reader }from '../../../../../assets/js/rdapi.js';


@Component({
  selector: 'sendCard',
  templateUrl: './sendCard.component.html',
})
export class sendCardComponent implements OnInit {
  showForm=true;
  g_device:string="00";
  g_isOpen:boolean= false;
  g_wantFunc:number=0;
  cardNo:string;
  validateForm!: FormGroup;
  param:any;
  @Input()
  set _param(value){
      if (!value) return;
      this.param = value;
    }
 
    desNum="";
    readData=0;//读出的数据
    pwd="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";//密钥
    num=0;//web认证的次数 现在设置为两次，两次不成功的话就不再继续
    inNum=0;//代表创建两个二进制文件
    select=0;//复位
    random=0;//获取随机数
    delfile=0;//擦除MF下的数据
    createSK=0;//创建密钥文件
    sk=0;//增加外部认证密钥
    createTwo=0;//创建二进制文件
    writeFile=0;//写入二进制文件
    readFile=0;//读取二进制文件

  submitForm(data) {
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
      if(this.validateForm.controls[key].invalid){
        return;
      }
    }
    let body={
      personId:this.param.personId,
      id:data.cardNo,
      cardNo:data.xnCardNo,
      cardCode:data.cardCode
    }
  this.http.post(this.api.manager.landlordBingdingCard.url,body).subscribe((res:any) => {
    console.log(res)
    if (res.status === '200') {
      this.msg.success('操作成功');
      this.modalRef.triggerOk();
    } else {
      this.msg.error(res.message)
    }
  })

}
constructor(
  private api: ApiService,
  private http: HttpClient,
  private msg: NzMessageService,
  private modalRef: NzModalRef,
  private util: UtilService,
  private fb: FormBuilder
) { }



  ngOnInit(): void {
    const that=this;
    this.validateForm = this.fb.group({
      cardNo:[null,[Validators.required]],
      cardCode:[null,[Validators.required]],
      xnCardNo:[null,[Validators.required]]
    });
    if(reader.SocketOpen){
      this.connect();
    }else{
      reader.createSocket();
      setTimeout(()=>{
        this.connect();
      },200)
    }
    reader.onResult((rData:any)=>{
      console.log(rData)
      this.inNum++;
      if(rData.strCmdCode == "1203"){
        let str=rData.strData;
        let a=str.substring(str.length-4,str.length);
        if(a != "9000" ){//证明出现错误
          if(this.delfile == 1){//代表密钥错误，需要用新的密钥，然后获取并发送八字节加密数据
            this.select=1;
            this.delfile=0;
            this.pwd="0123321456654789987ABCDEFFEDCBC1";//用新的密钥去认证
            if(this.num == 2){//如果认证两次依然错误的话，则不再继续
              this.msg.error('密钥错误')
              return;
            }
          }else{
            return;
          }
        }
      }

      if(this.readData == 1){//代表读取二进制文件
        this.checkCard();
       let n=rData.strData.slice(0,16);
       this.validateForm.patchValue({
        xnCardNo:n
      })
       this.readData=0;
      }
      
      if(this.select == 1 ){//获取随机数 已复位
        this.getRandom();
        this.random=1;
        this.select=0;
      }else if(this.random == 1 ){//发送八字节加密数据
        //获取八字节加密数据，然后发送八字节加密数据
        this.getDesNum(rData.strData.slice(0,16)).then((res)=>{
          this.getNumber();
        });
        this.num++;
        this.delfile=1;
        this.random=0;
      }else if(this.delfile == 1 ){
        this.delData();
        this.createSK=1;
        this.delfile=0;
      }else if(this.createSK == 1 ){
        this.createFile();
        this.sk=1;
        this.createSK=0;
      }else if(this.sk == 1 ){
        this.addSK();
        this.createTwo=1;
        this.sk=0;
      }else if(this.createTwo == 1 ){
        this.createHex();
        this.writeFile=1;
        this.createTwo=0;
        this.inNum=0;
      }else if(this.writeFile == 1 && this.inNum == 2){//index=2代表两个二进制文件已经创建完成，然后执行写二进制文件
        this.writeHex();
        this.writeFile=0;
        this.readFile=1;
        this.inNum=0;
      }else if(this.readFile == 1 && this.inNum == 2){//读取二进制文件  index=2代表两个二进制文件已经写入完成，可以执行读二进制文件
        this.readHex();
        this.readFile=0;
        this.readData=1;
      }



      switch(rData.strCmdCode){
        case "0007":
          if(rData.strStatus != "00"){
            this.msg.error("连接设备失败!");
          }else{
            this.g_isOpen=true;
            console.log("连接成功")
          }
          break;
        case "1001":
          if(rData.strStatus != "00"){
            return;
          }
          switch(this.g_wantFunc){
             case 1:
              reader.send(this.g_device + "1002"); //TyA_Anticollision
              break;
          }
          break;
        case "1002":
          if(rData.strStatus != "00"){
            return;
          }
          switch(this.g_wantFunc){
              case 1 :
                // that.validateForm.patchValue({
                //   cardNo:rData.strData
                // })
                // this.cardNo=rData.strData;
                // this.checkCard();
              break;
          }
          break;
          case "1202"://复位
            this.cardNo=rData.strData.slice(0,8);
            console.log("选择MF");
            reader.send(this.g_device + "1203" + "00A40000023F00");//选择MF
            this.select=1;
           break;
          case "2303":
            if(rData.strStatus == '00'){//寻卡成功之后发送读身份证物理卡号的命令
              reader.send(this.g_device + "2304")  //发送读身份证物理卡号的命令
            }
            break;
          case "2304":
            if(rData.strStatus == '00'){
              this.cardNo=rData.strData
              let n=rData.strData.slice(0,16);
              this.validateForm.patchValue({
                  xnCardNo:n
              })
          }
          break;
      }
     
    })
  }

  //卡号输入框失焦验证卡号是否已被绑定
  iptBlur(){
    this.checkCard();
  }

  //读卡或者输完卡号之后，检查此卡是否已经被绑定
checkCard(){
  if(this.cardNo == "" || this.cardNo == undefined){
    return;
  }
  const that=this;
  this.http.get(this.api.doorCard.checkCard.url+this.cardNo).subscribe((res:any)=>{
    console.log(res);
    if(res.status == 200){
      if(res.data != null && res.data.personId != "" && res.data.personId != null){
            this.msg.error("此卡已经被绑定!");
            setTimeout(function(){
              that.cardNo="";
              that.validateForm.patchValue({
                xnCardNo:""
              })
            },1000);
        }
    }
  })
}

  ngOnDestroy(){
    reader.Disconnect();
  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

  //获取标准日期格式
  getDate(str:string){
    const year=str.substring(0,4);
    const month=str.substring(4,6);
    const date=str.substring(6,8);
    return year+"-"+month+"-"+date;
  }

  connect(){
    reader.send(this.g_device + "0007" + "00"); //Open the USB device with index number 0. (打开索引号为0的USB设备)
    reader.send(this.g_device + "0109" + "41"); //Set to ISO14443a working mode. (设置为ISO14443A工作模式)
    reader.send(this.g_device + "0108" + "01"); //Turn on the reader antenna. (打开读卡器天线)
    this.LedGreen();
    setTimeout(()=>{this.LedRed()},200);
    reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
  }
  /**
   * Turn on the green light
   * (亮绿灯)
  **/
  LedGreen()
  {
    reader.send(this.g_device + "0107" + "02"); 
  }
  
  /**
   * Turn on the red light
   * (亮红灯)
  **/
  LedRed()
  {
    reader.send(this.g_device + "0107" + "01"); 
  }

  //读身份证
readID(){
  reader.send(this.g_device + "0109" + "42");//设置读写器射频工作模式，0x41:设置为TYPE_A方式，可读cpu卡,  0x42: 设置为TYPE_B方式，可读身份证物理卡号
	reader.send(this.g_device + "0108" + "00"); //Turn off the reader antenna. (关闭读卡器天线)
	reader.send(this.g_device + "0108" + "01"); //Turn on the reader antenna. (打开读卡器天线)   关闭打开天线可以为卡片重新上电
  reader.send(this.g_device + "2303" + "0");//寻卡
}


//读cpu卡
  read(){
    // if(this.g_isOpen != true){
    //   this.message.error("请连接读卡器!");
    //   return;
    // }
    reader.send(this.g_device + "0109" + "41");//设置读写器射频工作模式，0x41:设置为TYPE_A方式，可读cpu卡,  0x42: 设置为TYPE_B方式，可读身份证物理卡号
	  reader.send(this.g_device + "0108" + "00"); //Turn off the reader antenna. (关闭读卡器天线)
	  reader.send(this.g_device + "0108" + "01"); //Turn on the reader antenna. (打开读卡器天线)   关闭打开天线可以为卡片重新上电
    this.num=0;
    this.selectMF();
  }
  
  //复位之后才能发送cos命令
  selectMF(){
    console.log("复位");
    console.log(1);
    this.select=0;
    reader.send(this.g_device + "1202" + "26");//复位
  }
  
  //获取八字节随机数
  getRandom(){
    console.log("获取八字节随机数")
    console.log(2);
    reader.send(this.g_device + "1203" + "0084000008");//获取八字节随机数
  }
  
  //发送八字节加密数据
  getNumber(){
    console.log("发送八字节加密数据");
    console.log(3);
    console.log(this.desNum)
    reader.send(this.g_device + "1203" + "0082000008" + this.desNum);
  }
  //擦除MF下的数据
  delData(){
    console.log("擦除MF下的数据");
    console.log(4);
    //擦除MF下的数据
    reader.send(this.g_device + "1203" + "800E000000");
  }
  //建立密钥文件
  createFile(){
    //建立密钥文件
    console.log("建立密钥文件");
    console.log(5);
    reader.send(this.g_device + "1203" + "80E00000073F005001F1FFFF");
  }
  //增加外部认证密钥
  addSK(){
    console.log("增加外部认证密钥");
    console.log(6);
    reader.send(this.g_device + "1203" + "80D401001539F0F1AADD"+"0123321456654789987ABCDEFFEDCBC1");
    //reader.send(g_device + "1203" + "80D401000D39F0F1AADD"+"FFFFFFFFFFFFFFFF");
  }
  //创建二进制文件
  createHex(){
    console.log("创建二进制文件");
    console.log(7);
    reader.send(this.g_device + "1203" +"80E0001F07280020F0F1FFFF");//31号文件
    reader.send(this.g_device + "1203" +"80E0001A07280020F0F1FFFF");//26号文件
    
  }
  //写二进制文件
  writeHex(){
    console.log("写二进制文件");
    console.log(8);
    this.getDesNum(this.cardNo+"00000000").then((res)=>{
      console.log('虚拟卡号',this.desNum)
      reader.send(this.g_device + "1203" +"00D69F0008"+"8F4C3814C3B499A9");//31号文件
      reader.send(this.g_device + "1203" +"00D69A0008"+this.desNum);//26号文件
    })
   
  }
  //读二进制文件
  readHex(){
    console.log("读二进制文件");
    console.log(9);
    reader.send(this.g_device + "1203" +"00B09A0010");
  }
  
  //获取八字节加密数据
  getDesNum(randomNum){
   return  new Promise((resolve)=>{
      this.http.post("/core/door/card/desCard?data="+randomNum+"&password="+this.pwd,{}).subscribe((res:any)=>{
        console.log(res)
        this.desNum=res.data
        resolve(res.data)
      })
    })
  }

// //读卡
// readCpu(){
//   if(this.g_isOpen != true){
//     this.msg.error("请连接读卡器!");
//     return;
//   }
//   //Start read UID
//   reader.send(this.g_device + "1001" + "52"); //TyA_Request
//   this.g_wantFunc = 1;  
//   reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
// }

// //连接读卡器
// connect(){
// 	reader.send(this.g_device + "0007" + "00"); //Open the USB device with index number 0. (打开索引号为0的USB设备)
// 	reader.send(this.g_device + "0109" + "41"); //Set to ISO14443a working mode. (设置为ISO14443A工作模式)
// 	reader.send(this.g_device + "0108" + "01"); //Turn on the reader antenna. (打开读卡器天线)
//  this.LedGreen();
//  let that=this;
//   setTimeout(function(){that.LedRed()},200); 
//   reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
// }

// LedGreen(){
//  reader.send(this.g_device + "0107" + "02"); 
// }

// LedRed(){
//   reader.send(this.g_device + "0107" + "01"); 
// }

}
